/**
 * 简化测试服务器 - 用于诊断数据库和API问题
 */

import express from 'express';
import cors from 'cors';

// 模拟数据库数据
const mockData = {
  doctors: [
    {
      doctor_id: 1,
      username: 'admin',
      password_hash: 'hashed_password',
      real_name: '系统管理员',
      department: '系统管理',
      title: '管理员',
      role: 3,
      status: 1
    }
  ],
  patients: [
    {
      patient_id: 1,
      patient_code: 'P001',
      gender: 1,
      birthday: '1990-01-01',
      phone: '13800138000',
      address: '测试地址'
    }
  ],
  scoring_tasks: [],
  scoring_results: []
};

const app = express();
app.use(cors());
app.use(express.json());

// 测试API
app.get('/api/test', (req, res) => {
  res.json({
    success: true,
    message: 'API服务正常',
    timestamp: new Date().toISOString()
  });
});

// 登录接口
app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body;

  console.log('登录请求:', { username, password });

  if (username === 'admin' && password === 'admin123') {
    const doctor = mockData.doctors.find(d => d.username === username);
    res.json({
      success: true,
      data: {
        token: 'mock_jwt_token_' + Date.now(),
        doctor: {
          doctor_id: doctor.doctor_id,
          username: doctor.username,
          real_name: doctor.real_name,
          role: doctor.role
        }
      }
    });
  } else {
    res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }
});

// 获取评分任务
app.get('/api/scoring/tasks', (req, res) => {
  res.json({
    success: true,
    data: mockData.scoring_tasks,
    total: mockData.scoring_tasks.length
  });
});

// 获取患者列表
app.get('/api/patients', (req, res) => {
  res.json({
    success: true,
    data: mockData.patients,
    total: mockData.patients.length
  });
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    status: 'healthy',
    services: {
      api: 'healthy',
      database: 'mock',
      ai_service: 'unknown'
    }
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  });
});

const PORT = 4000;
app.listen(PORT, () => {
  console.log(`🚀 测试服务器启动成功！`);
  console.log(`📍 端口: ${PORT}`);
  console.log(`🔗 API地址: http://localhost:${PORT}`);
  console.log(`📝 测试账户: admin / admin123`);
  console.log(`📊 健康检查: http://localhost:${PORT}/api/health`);
  console.log(`🧪 API测试: http://localhost:${PORT}/api/test`);
});